package com.ccp.dev.workflow.service.bpm.cmd;

import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.workflow.model.NodeCache;
import com.ccp.dev.workflow.model.bpm.ProcessCmd;
import com.ccp.dev.workflow.service.bpm.thread.TaskThreadService;
import org.flowable.common.engine.impl.interceptor.Command;
import org.flowable.common.engine.impl.interceptor.CommandContext;
import org.flowable.engine.impl.persistence.entity.ExecutionEntity;
import org.flowable.engine.impl.util.CommandContextUtil;
import org.flowable.task.service.impl.persistence.entity.TaskEntity;

/**
 * ClassDescribe:
 * 判断在审批过程中是否属于子流程的驳回。
 * <pre>
 * 1.判断是否为驳回指令。
 * 2.如果不是驳回动作，那么直接返回false。
 * 3.判断当前任务是否为子流程实例。
 * 4.如果是判断当前节点是否是子流程的第一个节点，如果是那么允许驳回。
 * </pre>
 * @author :wangcheng
 * Date: 2019-11-13
 */
public class AllowBackCallActivityCmd implements Command<Boolean> {

    private String taskId = "";

    public AllowBackCallActivityCmd(String taskId) {
        this.taskId = taskId;
    }

    @Override
    public Boolean execute(CommandContext commandContext) {
        ProcessCmd processCmd = TaskThreadService.getProcessCmd();
        if (processCmd.isBack() != 1) {
            return false;
        }
        TaskEntity task = CommandContextUtil.getTaskService().getTask(taskId);
        String processInstanceId = task.getProcessInstanceId();
        ExecutionEntity executionEntity = CommandContextUtil.getExecutionEntityManager().findById(processInstanceId);
        if (executionEntity == null) {
            return false;
        }

        String superExecutionId = executionEntity.getSuperExecutionId();
        // 判断当前是否是子流程实例
        if (StringUtil.isEmpty(superExecutionId)) {
            return false;
        }
        // 判断当前是否是第一个节点
        String procDefId = task.getProcessDefinitionId();
        String nodeId = task.getTaskDefinitionKey();
        boolean rtn = NodeCache.isFirstNode(procDefId, nodeId);
        // 获取当前节点的配置，判断是否是分发节点， 是则不能有
        return rtn;
    }
}
